package com.hup.joystick.view.customView;

import com.hup.utils.commons.hardware.ScreenUtil;
import com.hup.utils.swing.ComponentUtil;
import com.hup.utils.swing.frame.BaseJWindow;
import lombok.extern.log4j.Log4j2;

import javax.swing.*;
import java.awt.*;
import java.util.HashSet;
import java.util.Iterator;

/**
 * @author hugan
 * @date 2020/11/19
 */
@Log4j2
public class BaseMenuWindow extends BaseJWindow {
    /**
     * 全屏JWindow菜单的半透明背景色
     */
    public static final Color TRANSPARENT_MENU_BG = new Color(180, 180, 180, 180);

    /**
     * 所有在展示的菜单
     */
    private static final HashSet<BaseMenuWindow> SHOWING_MENU = new HashSet<>();

    public BaseMenuWindow(String title) {
        super(null, title);
    }

    public BaseMenuWindow(Window owner, String title) {
        super(owner, title);
    }

    /**
     * 初始化控件背景:
     * .窗口大小是全屏,contentPane背景是无限透明,且实现点击屏幕退出菜单
     * .contentPane里只含一个JPanel,背景色是 TRANSPARENT_MENU_BG,
     *
     * @param childToFix 需要适配透明背景的控件,不同控件是要不同背景色的:如JPanel,ImageButton,会重复绘制的JLabel(不用重复绘制的JLabel是不用处理的)
     */
    protected void initTransparentBg(JComponent... childToFix) {
        //全屏窗口背景:无限透明,且能接收鼠标事件
        setBackground(new Color(0, 0, 0, 1));
        //实际装控件的panel:有背景色
        ComponentUtil.setBackground((JComponent) getContentPane().getComponent(0), TRANSPARENT_MENU_BG);
        //需要设置透明背景的子控件
        Color transparentColor = new Color(0, 0, 0, 0);
        for (JComponent c : childToFix) {
            if (c instanceof JPanel) {
                //panel背景要真透明像素,否则是原背景色叠加
                ComponentUtil.setBackground(c, transparentColor);
            } else if (c instanceof JLabel) {
                //包括ImageButton,OpaqueLabel:要用 AlphaComposite.Src 直接覆盖颜色
                ComponentUtil.setBackground(c, TRANSPARENT_MENU_BG);
            } else {
                throw new IllegalArgumentException("未适配:" + c.getClass().getSimpleName());
            }
        }
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        if (b) SHOWING_MENU.add(this);
    }

    @Override
    public void dispose() {
        super.dispose();
        SHOWING_MENU.remove(this);
    }

    /**
     * 显示菜单窗口:
     * .全屏居中
     */
    protected void showMenuWindow() {
        Dimension screenSize = ScreenUtil.getScreenSize();
        setSize(screenSize);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    @SuppressWarnings("WhileLoopReplaceableByForEach")
    public static void disposeShowingWindows() {
        log.info("size={}", SHOWING_MENU.size());
        //不能直接用for,因为dispose中有remove
        Iterator<BaseMenuWindow> iterator = SHOWING_MENU.iterator();
        while (iterator.hasNext()) iterator.next().dispose();
    }

}
